import { lclass, rclass } from "../../types/index"
interface Istate {
    detailList: rclass[],
    leftList: lclass[],
    rightList: rclass[],
    cartList:rclass[],
    checkAll:boolean
}
let intiState = {
    //详情数据
    detailList: [],
    //左侧数据
    leftList: [],
    //右侧数据
    rightList:[],
    //购物车
    cartList:[],
    //全选
    checkAll:false
}
export default (state = intiState, action: any) => {
    console.log(action.type)
    let newState = JSON.parse(JSON.stringify(state))
    switch (action.type) {
        case "LEFT_NAV":
            newState.leftList = action.list;
            return newState;
        case "RIGHT_SHOP":
            newState.rightList = action.list;
            return newState;
        case "DETAIL_SHOP":
            newState.detailList = action.list;
            return newState;
        case "ADD_CART":
            let flag = newState.cartList.some((item:rclass)=>item.id === action.item.id)
            if(!flag){
                action.item.num = 1;
                action.item.isflag =true;
                newState.cartList.push(action.item)
            }else{
                newState.cartList.forEach((item:rclass)=>item.id === action.item.id ? item.num++ : item.num)
            }
            newState.checkAll = newState.cartList.every((item:rclass)=>item.isflag)
            return newState;
        case "CHANGE_COUNT":
            let index= newState.cartList.findIndex((item:rclass)=>item.id === action.id)
            newState.cartList.forEach((item:rclass)=>{
                if(item.id === action.id){
                    if(action.flag){//减
                        item.num--;
                        if(item.num <= 1){
                            newState.cartList.splice(index,1)
                        }
                    }else{
                        item.num++
                    }
                }
                
            })
            return newState
        case "CHANGE_FLAG":
            //每一项checkbox
            newState.cartList.forEach((item:rclass)=>item.id===action.id ? item.isflag = action.checked : item.isflag)
            //反选
            newState.checkAll = newState.cartList.every((item:rclass)=>item.isflag)
            return newState
        case "CHECK_ALL":
            //全选状态
            newState.checkAll = action.checkall;
            //全选
            newState.cartList.forEach((item:rclass)=>item.isflag = action.checkall)
            return newState
        default:
            return state;
    }
}